// 排序方式
function js_main1(strs) {
  if (strs.length === 0) return [];
  let map = new Map();
  strs.forEach((str) => {
    const key = str.split("").sort().join("");
    map.has(key) ? map.get(key).push(str) : map.set(key, [str]);
  });
  return Array.from(map.values());
}

// hash统计分析法
function js_main2(strs) {
  const result = [];
  const used = new Array(26).fill(false);
  for (let i = 0; i < strs.length; i++) {
    if (used[i]) continue;
    const temp = [strs[i]];
    for (let j = i + 1; j < strs.length; j++) {
      if (used[j]) continue;
      if (strs[i].length !== strs[j].length) continue;
      let isAnagram = true;
      const map = {};
      for (const char1 of strs[i]) {
        map[char1] = !map[char1] ? 1 : map[char1] + 1;
      }
      for (const char2 of strs[j]) {
        if (!map[char2]) {
          isAnagram = false;
          break;
        }
        map[char2]--;
      }
      if (isAnagram) {
        used[j] = true;
        temp.push(strs[j]);
      }
    }
    result.push(temp);
  }
  return result;
}

// 暴力解法，利用字符的 ASCII码 建立数组分析
function js_main3(strs) {
  const map = {};
  const toString = nums => nums.map((num, index) => `${index}@${num}`).join('$');
  for (let str of strs) {
    const count = new Array(26).fill(0);
    for (let char of str) {
      count[char.charCodeAt(0) - 'a'.charCodeAt(0)]++;
    }
    const key = toString(count);
    map[key] ? map[key].push(str) : map[key] = [str];
  }
  return Object.values(map);
}

console.log(js_main1(["eat", "tea", "tan", "ate", "nat", "bat"]));
console.log(js_main1([""]));
console.log(js_main1(["a"]));
console.log(js_main2(["eat", "tea", "tan", "ate", "nat", "bat"]));
console.log(js_main2([""]));
console.log(js_main2(["a"]));
console.log(js_main3(["eat", "tea", "tan", "ate", "nat", "bat"]));
console.log(js_main3([""]));
console.log(js_main3(["a"]));
